import React from 'react'
import { UdTable, IUdColumn, columnRenders } from '@/lib'
import { InputNumber } from 'antd'
import dayjs from 'dayjs'

enum EModifyType {
  UP = '调增',
  DOWN = '调减'
}

function TerminalTable(props: ITerminalTableProps) {
  const { dataSource, changeTableData } = props

  const changeData = (row, key, e) => {
    const value = e.target.value || undefined
    const oldQuotaNum = row.quotaNum // 原配额数量
    const quotaCanNum = row.quotaCanNum // 剩余可用数量
    let multiple = 1
    if (row.modifyType === 'DOWN') {
      multiple = -1
    }
    // 调整后剩余可用数量
    row.modifyAfterNum = quotaCanNum + (multiple * value)
    // 调整后配额总量
    row.modifyAfterQuota = oldQuotaNum + (multiple * value)

    const index = dataSource.findIndex(data => data.id === row.id)
    const newData = [ ...dataSource ]
    newData.splice(index, 1, { ...row, [key]: value })
    changeTableData(newData)
  }

  const columns: IUdColumn[] = [
    { title: '序号', dataIndex: 'id', render: (text, record, index) => index + 1 },
    { title: '客户名称', dataIndex: 'dealerName' },
    { title: '客户类型', dataIndex: 'dealerType' },
    { title: '物料分类名称', dataIndex: 'groupName' },
    { title: '配额有效期', dataIndex: 'quotaStartTime', render: (text, record) => {
      let render
      render = text ? dayjs(text).format('YYYY-MM-DD') : ''
      render +=  record.quotaEndTime ? '~' + dayjs(record.quotaEndTime).format('YYYY-MM-DD') : ''
      return render
    } },
    { title: '原配额数量', dataIndex: 'quotaNum' },
    { title: '已使用数量', dataIndex: 'quotaUseNum' },
    { title: '剩余可用数量', dataIndex: 'quotaCanNum' },
    { title: '调整类型', dataIndex: 'modifyType', render: columnRenders.enum(EModifyType) },
    { title: '调整数量', dataIndex: 'modifyNum',
      // 暂时不可修改调整数量
      // render: (text, record) => {
      //   return <InputNumber defaultValue={text} onBlur={(e) =>changeData(record, 'modifyNum', e)} min={0} />
      // }
    },
    { title: '调整后剩余可用数量', dataIndex: 'modifyAfterNum' },
    { title: '调整后配额总数量', dataIndex: 'modifyAfterQuota' },
    { title: '备注', dataIndex: 'remark' },
  ]

  return (
    <UdTable
      className='nowarp-th'
      dataSource={dataSource}
      columns={columns}
      pagination={false}
      rowKey='id'
    />
  )
}

export default React.memo(TerminalTable)

interface ITerminalTableProps {
  dataSource: any[]
  changeTableData: (data: any) => void
}
